package com.ming.service;

import io.minio.MinioClient;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import org.xmlpull.v1.XmlPullParserException;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * @Author:weiming
 * @Date:2020/12/1
 */
@Service
public class FileService {
    String Base_Url = ResourceUtils.getURL("classpath:").getPath()+"/static/upload/";

    @Value("${minio.endpoint}")
    private String ENDPOINT;
    @Value("${minio.bucketName}")
    private String BUCKET_NAME;
    @Value("${minio.accessKey}")
    private String ACCESS_KEY;
    @Value("${minio.secretKey}")
    private String SECRET_KEY;


    public FileService() throws FileNotFoundException {
    }


    /**
     * 单文件上传
     * @param file
     * @return
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {
        if (file.isEmpty()){
            return "文件不能为空!";
        }

        //真实路径
        String  realPath =  ResourceUtils.getURL("classpath:").getPath()+"/static";
        System.out.println(realPath);

        //file对象
        File fileUpload =  new File(realPath, file.getOriginalFilename());
        file.transferTo(fileUpload);

        return "上传成功";
    }

    /**
     * 多文件上传
     * @param fileList
     * @return
     * @throws IOException
     */
    public String multiUploadFile(List<MultipartFile> fileList) throws IOException {
        //真实路径
        String  realPath =  ResourceUtils.getURL("classpath:").getPath()+"/static/upload";
        for (int i = 0; i<fileList.size(); i++){
            //获取每个文件
            MultipartFile file  = fileList.get(i);
            if(file.isEmpty()) {
                continue;
            }
            File fileUpload =  new File(realPath, file.getOriginalFilename());
            file.transferTo(fileUpload);
            System.out.println("文件"+(i+1)+"上传成功");
        }
        return "上传成功";
    }

    /**
     * 文件下载
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     */
    public String download(HttpServletResponse response) throws UnsupportedEncodingException {
        File file = new File(Base_Url+"p1.jpg");
        //文件名
        String fileName = file.getName();

        // 清空缓冲区，状态码和响应头(headers)
        response.reset();
        // 设置ContentType，响应内容为二进制数据流，编码为utf-8，此处设定的编码是文件内容的编码
        response.setContentType("application/octet-stream;charset=utf-8");
        // 以（Content-Disposition: attachment; filename="filename.jpg"）格式设定默认文件名，设定utf编码，此处的编码是文件名的编码，使能正确显示中文文件名
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"),"iso-8859-1"));

        //下载
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            // 获取字节流
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            System.out.println("Download successfully!");
            return "下载成功";
        }
        catch (Exception e) {
            System.out.println("Download failed!");
        }
        finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return "下载失败";
    }

    /**
     * Minio对象文件上传
     * @param file
     */
    public String minioUpload(MultipartFile file) {
        try {
            // 使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
            MinioClient minioClient = new MinioClient(ENDPOINT, ACCESS_KEY, SECRET_KEY);
            System.out.println("创建成功");
            // 检查存储桶是否已经存在
            boolean isExist = minioClient.bucketExists(BUCKET_NAME);
            if(isExist) {
                System.out.println("Bucket already exists.");
            } else {
                // 创建存储桶
                minioClient.makeBucket(BUCKET_NAME);
            }

            // 使用putObject上传一个文件到存储桶中。
            minioClient.putObject(BUCKET_NAME,file.getOriginalFilename(), file.getInputStream(),file.getContentType());
            String file_Url = new String(ENDPOINT+"/"+BUCKET_NAME+"/"+file.getOriginalFilename());
            return file_Url;
        } catch(MinioException | NoSuchAlgorithmException | IOException | InvalidKeyException | XmlPullParserException e) {
            System.out.println("Error occurred: " + e);
        }

        return "上传失败";
    }
}
